layui.use(['form', 'element'], function () {
    var form = layui.form;
    var e = layui.element;
    form.on('submit(lookuser)', function (data) {
        $.ajax({
            url: basePath + "/chat/lkuser/" + data.field.username,
            data: "",
            contentType: "application/json;charset=UTF-8", //发送数据的格式
            type: "post",
            dataType: "json", //回调
            beforeSend: function () {
                layer.load(1, {
                    content: '查询中...',
                    success: function (layero) {
                        layero.find('.layui-layer-content').css({
                            'padding-top': '39px',
                            'width': '60px'
                        });
                    }
                });
            },
            complete: function () {
                layer.closeAll('loading');
            },
            success: function (data) {
                if (data.code != 200) {
                    layer.msg(data.message, {
                        time: 1500,
                        icon: 2,
                        offset: '350px'
                    });
                } else {
                    setUserInfo(data.data.userinfo);
                }
            }
        });
        return false;
    });
});

var editIndex;
var layedit;
var glayedit;
layui.use(['form', 'layedit', 'laydate'], function () {
    var form = layui.form,
        layer = layui.layer;
    layedit = layui.layedit;
    //创建一个编辑器
    editIndex = layedit.build('LAY_demo_editor', {
        tool: ['strong' //加粗
            , 'italic' //斜体
            , 'underline' //下划线
            , '|' //分割线
        ],
        height: 120 //设置编辑器高度
    });

    form.verify({
        content: function () {
            layedit.sync(editIndex)
        }
    });
    form.render();
});
layui.use(['form', 'layedit', 'laydate'], function () {
    var form = layui.form,
        layer = layui.layer;
    glayedit = layui.layedit;
    //创建一个编辑器
    geditIndex = glayedit.build('GLAY_demo_editor', {
        tool: ['strong' //加粗
            , 'italic' //斜体
            , 'underline' //下划线
            , '|' //分割线
        ],
        height: 120 //设置编辑器高度
    });

    form.verify({
        content: function () {
        	glayedit.sync(geditIndex)
        }
    });
    form.render();
});
document.onkeydown = function (event) {
    var e = event || window.event;
    if (e && e.keyCode == 13) { //回车键的键值为13
        send();
    }
};

/*控制鼠标移动到div显示或者隐藏div的滚动*/
function leftscroll(id) {
    if (id == 1) {
        document.getElementById("leftscroll").style.overflowY = "auto";
        document.getElementById("leftscroll").style.overflowX = "hidden";
    } else if (id == 2) {
        document.getElementById("leftscroll").style.overflowY = "hidden";
        document.getElementById("leftscroll").style.overflowX = "hidden";
    } else if (id == 3) {
        document.getElementById("msgcontent").style.overflowY = "auto";
        document.getElementById("msgcontent").style.overflowX = "hidden";
    } else if (id == 4) {
        document.getElementById("msgcontent").style.overflowY = "hidden";
        document.getElementById("msgcontent").style.overflowX = "hidden";
    }
}
/*控制鼠标移动到div显示或者隐藏div的滚动*/
function gleftscroll(id) {
    if (id == 1) {
        document.getElementById("gleftscroll").style.overflowY = "auto";
        document.getElementById("gleftscroll").style.overflowX = "hidden";
    } else if (id == 2) {
        document.getElementById("gleftscroll").style.overflowY = "hidden";
        document.getElementById("gleftscroll").style.overflowX = "hidden";
    } else if (id == 3) {
        document.getElementById("groupmsgcontent").style.overflowY = "auto";
        document.getElementById("groupmsgcontent").style.overflowX = "hidden";
    } else if (id == 4) {
        document.getElementById("groupmsgcontent").style.overflowY = "hidden";
        document.getElementById("groupmsgcontent").style.overflowX = "hidden";
    }
}
var info = new Vue({
    el: '#userinfo',
    data() {
        return {
            userinfo: []
        }
    },
    mounted: function () {
        window.setUserInfo = this.setUserInfo;
    },
    methods: {
        /**添加好友查询用户信息*/
        setUserInfo: function (info) {
            var that = this;
            that.userinfo = info;
            $("#info").show();
        },adduser:function (uid) {
            $.ajax({
                url: basePath + "/chat/adduser/" + uid,
                data: "",
                contentType: "application/json;charset=UTF-8", //发送数据的格式
                type: "post",
                dataType: "json", //回调
                beforeSend: function () {
                    layer.load(1, {
                        content: '添加中...',
                        success: function (layero) {
                            layero.find('.layui-layer-content').css({
                                'padding-top': '39px',
                                'width': '60px'
                            });
                        }
                    });
                },
                complete: function () {
                    layer.closeAll('loading');
                },
                success: function (data) {
                	$('#info').hide();
                    if (data.code != 200) {
                        layer.msg(data.message, {
                            time: 1500,
                            icon: 2,
                            offset: '350px'
                        });
                    } else {
                        layer.msg(data.message, {
                            time: 1000,
                            icon: 1,
                            offset: '350px'
                        }, function () {
                            getlistnickname();//刷新好友列表
                        });
                    }
                }
            });
        }
    }
})
var actuserid = null;
var app = new Vue({
    el: '#vuechat',
    data() {
        return {
            listnickname: [],
            listmessage: [],
            loginusername: userid
        }
    },
    mounted: function () {
        this.getlistnickname();
        window.alertnote = this.alertnote;
        window.activeuser = this.activeuser;
        window.appendmsg = this.appendmsg;
        window.getlistnickname=this.getlistnickname;
    },
    methods: {
        /*新信息提示*/
        alertnote: function (msgtouid) {
            var that = this;
            document.getElementById(msgtouid).style.backgroundColor = '#E6A23C';
            /*for (var i = 0; i < that.listnickname.length; i++) {
                console.log(that.listnickname[i].userid);
                if (that.listnickname[i].userid === msgtouid) {
                    layer.msg(that.listnickname[i].nickname + '发来一条信息', {
                        time: 1500,
                        icon: 0,
                        offset: '50px'
                    });
                }
            }*/
        },
        /*添加聊天记录*/
        appendmsg(mstype, revive, send, text) {
            var that = this;
            that.listmessage.push({msgType: mstype, reciveUserId: revive, sendUserId: send, sendText: text});
            setTimeout(function () {
                document.getElementById("msg_end").scrollIntoView();
            }, 500)
        },
        /*设置点击左侧的列表的时候切换样式同时查找聊天记录*/
        selectStyle: function (item, acuserid) {
        	getlistnickname();
            this.$nextTick(function () {
                this.listnickname.forEach(function (item) {
                	 Vue.set(item, 'active', false);
                    var bkcolor = document.getElementById(item.userid).style.backgroundColor;
                    if(bkcolor != 'rgb(230, 162, 60)'){
                    	 document.getElementById(item.userid).style.backgroundColor = '#FAFAFA';
                    }
                });
                Vue.set(item, 'active', true);
                document.getElementById(item.userid).style.backgroundColor = '#EBEBEC';
            });
            this.getMessageList(userid,acuserid);
            actuserid = acuserid;
            
        },
        /*获取左侧的聊天窗口*/
        getlistnickname: function () {
            var that = this;
            $.ajax({
                url: basePath + "/chat/lkfriends",
                data: "",
                contentType: "application/json;charset=UTF-8",
                type: "post",
                dataType: "json",
                success: function (response) {
                	if(response.code=='200') {
                		that.listnickname = response.data.friendsInfo;;
                	}
                    document.getElementById('leftc').style.display = 'block';
                    document.getElementById('appLoading').style.display = 'none';
                },
                error: function (err) {
                    console.log("err:", err);
                }
            });
        },
        /*获取聊天记录*/
        getMessageList: function (userid,acuserid) {
            document.getElementById('waits').style.display = 'none';
            document.getElementById('words').style.display = 'none';
            document.getElementById('appLoading2').style.display = 'block';
            var that = this;
            $.ajax({
                type: 'post',
                url: basePath + '/chat/lkuschatmsg/' + userid+"&"+acuserid,
                dataType: 'json',
                contentType: "application/json;charset=UTF-8",
                success: function (response) {
                	if(response.code=='200') {
                		that.listmessage = response.data.chatInfo;;
                	}
                    document.getElementById('words').style.display = 'block';
                    document.getElementById('appLoading2').style.display = 'none';
                    $('#msgcontent').ready(
                        function () {
                            setTimeout(function () {
                                document.getElementById("msg_end").scrollIntoView();
                            }, 500)
                        }
                    );
                },
                error: function (err) {
                    console.log("err:", err);
                }
            })
        },
        /*获取头像*/
        showUserImg: function (sendUserId) {
            var that = this;
            var groupUserImg='';
            $.ajax({
                type: 'post',
                url: basePath + '/chat/getUserImg/' + sendUserId,
                dataType: 'json',
                async: false ,
                contentType: "application/json;charset=UTF-8",
                success: function (response) {
                	if(response.code=='200') {
                		groupUserImg = response.data.UserImg;
                	}
                	
                },
                error: function (err) {
                    console.log("err:", err);
                }
            })
            return groupUserImg;
        }
    }
})
var groupid = null;
var app = new Vue({
    el: '#groupchat',
    data() {
        return {
            listgroupname: [],
            listgroupmessage: [],
            loginusername: userid
        }
    },
    mounted: function () {
        this.getlistgroupname();
        window.appendGroupmsg = this.appendGroupmsg;
        window.getlistgroupname=this.getlistgroupname;
    },
    methods: {
        /*添加聊天记录*/
    	appendGroupmsg(mstype, send, text) {
            var that = this;
            that.listgroupmessage.push({msgType: mstype, sendUserId: send, sendText: text});
            setTimeout(function () {
                document.getElementById("groupmsg_end").scrollIntoView();
            }, 500)
        },
        /*设置点击左侧的列表的时候切换样式同时查找聊天记录*/
        selectStyleforGroup: function (item, acgroupid) {
            this.$nextTick(function () {
                this.listgroupname.forEach(function (item) {
                    Vue.set(item, 'active', false);
                });
                Vue.set(item, 'active', true);
            });
            this.getGroupMessageList(acgroupid);
            groupid = acgroupid;
        },
        /*获取左侧的聊天窗口*/
        getlistgroupname: function () {
            var that = this;
            $.ajax({
                url: basePath + "/chat/listGroup",
                data: "",
                contentType: "application/json;charset=UTF-8",
                type: "post",
                dataType: "json",
                success: function (response) {
                	if(response.code=='200') {
                		that.listgroupname = response.data.userGroup;;
                	}
                    document.getElementById('groupleftc').style.display = 'block';
                    document.getElementById('groupappLoading').style.display = 'none';
                },
                error: function (err) {
                    console.log("err:", err);
                }
            });
        },
        /*获取聊天记录*/
        getGroupMessageList: function (acgroupid) {
            document.getElementById('groupwaits').style.display = 'none';
            document.getElementById('groupwords').style.display = 'none';
            document.getElementById('groupappLoading2').style.display = 'block';
            var that = this;
            $.ajax({
                type: 'post',
                url: basePath + '/chat/listgroupchatmsg/' + acgroupid,
                dataType: 'json',
                contentType: "application/json;charset=UTF-8",
                success: function (response) {
                	if(response.code=='200') {
                		that.listgroupmessage = response.data.groupChatMsg;;
                	}
                    document.getElementById('groupwords').style.display = 'block';
                    document.getElementById('groupappLoading2').style.display = 'none';
                    $('#groupmsgcontent').ready(
                        function () {
                            setTimeout(function () {
                                document.getElementById("groupmsg_end").scrollIntoView();
                            }, 500)
                        }
                    );
                },
                error: function (err) {
                    console.log("err:", err);
                }
            })
        },
        /*获取群内昵称*/
        showGroupNickName: function (sendUserId) {
            var that = this;
            var groupNickName='';
            $.ajax({
                type: 'post',
                url: basePath + '/chat/getNickName/' + sendUserId+"&"+groupid,
                dataType: 'json',
                async: false ,
                contentType: "application/json;charset=UTF-8",
                success: function (response) {
                	if(response.code=='200') {
                		groupNickName = response.data.nickName;
                	}
                	
                },
                error: function (err) {
                    console.log("err:", err);
                }
            })
            return groupNickName;
        },
        /*获取群内头像*/
        showUserImg: function (sendUserId) {
            var that = this;
            var groupUserImg='';
            $.ajax({
                type: 'post',
                url: basePath + '/chat/getUserImg/' + sendUserId,
                dataType: 'json',
                async: false ,
                contentType: "application/json;charset=UTF-8",
                success: function (response) {
                	if(response.code=='200') {
                		groupUserImg = response.data.UserImg;
                	}
                	
                },
                error: function (err) {
                    console.log("err:", err);
                }
            })
            return groupUserImg;
        }
    }
})
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
    //连接WebSocket节点
    websocket = new WebSocket("ws://localhost:8080/websocket/" + userid);
} else {
    alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
    //setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function (event) {
    //setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
    setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
    //setMessageInnerHTML("close");
}
//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
    websocket.close();
};

//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
    var msgs = innerHTML.split("|");
    if(msgs[0] === "sys"){
    	layer.msg(msgs[1], {
            time: 10000,
            icon: 0,
            offset: '150px'
        });
    }
    if(msgs[2] === '0' || msgs[0] === "0"){
    	if (msgs[0] === actuserid) {
            appendmsg("0", actuserid, msgs[0], msgs[1]);
        } else if (msgs[0] === "0") {
            layer.msg('当前用户不在线', {
                time: 1500,
                icon: 0,
                offset: '50px'
            });
        }else {
            alertnote(msgs[0])
        }
    	document.getElementById("msg_end").scrollIntoView();
    }
    if(msgs[2] === '1') {
    	if (msgs[0] === ''+groupid) {
            appendGroupmsg(msgs[2], msgs[3], msgs[1]);
    	}
    	document.getElementById("groupmsg_end").scrollIntoView();
    }
    
    
}

//关闭连接
function closeWebSocket() {
    websocket.close();
}

//发送消息
function send() {
    //var layedit = layui.layedit;
    var message = layedit.getContent(editIndex);
    if (message.length == 0) {
        layer.msg("请输入发送的内容", {
            time: 2500,
            icon: 2,
            offset: "300px"
        });
        return;
    }
    // 将内容设置为空
    layedit.setContent(editIndex, "", false);
    var object = new Object();
    object["sendUserId"] = userid;
    object["reciveUserId"] = actuserid;
    object["msgType"] = 0;
    object["sendText"] =message;
    var jsonData = JSON.stringify(object);
    websocket.send(jsonData);//websocket发送数据
    appendmsg("0", actuserid, userid, message);//vue追加聊天数据
    document.getElementById("msg_end").scrollIntoView();
}
//发送群聊消息
function groupSend() {
    var message = glayedit.getContent(geditIndex);
    if (message.length == 0) {
        layer.msg("请输入发送的内容", {
            time: 2500,
            icon: 2,
            offset: "300px"
        });
        return;
    }
    // 将内容设置为空
    glayedit.setContent(geditIndex, "", false);
    var object = new Object();
    object["sendUserId"] = userid;
    object["groupId"] = groupid;
    object["msgType"] = 1;
    object["sendText"] =message;
    var jsonData = JSON.stringify(object);
    websocket.send(jsonData);//websocket发送数据
    appendGroupmsg("1", userid, message);//vue追加聊天数据
    document.getElementById("groupmsg_end").scrollIntoView();
}
//layui面板刷新保留在当前面板
$(".layui-tab-title li").click(function () {
    var picTabNum = $(this).index();
    sessionStorage.setItem("picTabNum", picTabNum);
});
$(function () {
    var getPicTabNum = sessionStorage.getItem("picTabNum");
    $(".layui-tab-title li").eq(getPicTabNum).addClass("layui-this").siblings().removeClass("layui-this");
    $(".layui-tab-content>div").eq(getPicTabNum).addClass("layui-show").siblings().removeClass("layui-show");
})

// 定义注册组件
const main ={
    template : '#showgroup'
}

//创建群组件
const create_group_component = {
    template: '#creategroup',
    data: function () {
        return {
            form: {
                groupname: ''
            }
        }
    },
    methods:{
        ajaxCreategroup : function () {
            //1、建群的同时将创建者用户id放到群聊里
            //2、创建成功,回到聊天列表
            var vm = this;
            var groupname = vm.form.groupname;
            if (groupname.length===0) {
                layer.tips("群名称不能为空，请输入", '#creategroupName', {
                    tips: [1, "#0FA6D8"],
                    tipsMore: !1,
                    time: 2000
                });
                $("#creategroupName").focus();
                return false;
            }


            let params = {"groupName":groupname };

            axios.post('/chat/createGroupInfo',
                params
            ).then(function(response) {
                console.log(response);
                if(response.data.code=='200'){
                    layer.msg(response.data.message, {
                        time: 1000,
                        icon: 1,
                        offset: '350px'
                    }, function () {
						// 刷新群组列表
                    	getlistgroupname();
                        vm.form.groupname ="";//页面跳转前清空输入的群名称
                        $('li:first').click();
                    });

                }else{
                    layer.msg(response.data.message, {
                        time: 1500,
                        icon: 2,
                        offset: '350px'
                    });
                }
            }).catch(function(error) {
                console.log(error);
            });

        }
    }
};
//搜索
const search_group_component = {
    template: '#searchgroup',
    data: function () {
        return {
            form: {
                groupname: ''
            },
            groupinfo : []

        }
    },
    mounted: function () {
        window.setGroupinfo = this.setGroupinfo;
    },
    methods:{
        addGroup : function(groupid){
            let params = {"groupId":groupid };

            axios.post('/chat/addToChatGroup',
                params
            ).then(function(response) {
                console.log(response);
                if(response.data.code=='200'){
                    layer.msg(response.data.message, {
                        time: 1000,
                        icon: 1,
                        offset: '350px'
                    }, function () {
                    	// 刷新群组列表
                    	getlistgroupname();
                        $("#groupinfoshow").hide();

                    });

                }else{
                    layer.msg(response.data.message, {
                        time: 1500,
                        icon: 2,
                        offset: '350px'
                    },function () {
                        $("#groupinfoshow").hide();
                    });
                }
            }).catch(function(error) {
                console.log(error);
            });
        },
        setGroupinfo : function(info){
            var that = this;
            this.groupinfo = info;
        },
        ajaxSearchgroup : function () {
            var vm = this;
            var groupname = vm.form.groupname;
            if (groupname.length===0) {
                layer.tips("群名称不能为空，请输入", '#searchgroupName', {
                    tips: [1, "#0FA6D8"],
                    tipsMore: !1,
                    time: 2000
                });
                $("#searchgroupName").focus();
                return false;
            }


            let params = {"groupName":groupname };

            axios.post('/chat/searchGroupInfo',
                params
            ).then(function(response) {
                console.log(response);
                if(response.data.code=='200'){
                    layer.msg(response.data.message, {
                        time: 1000,
                        icon: 1,
                        offset: '350px'
                    }, function () {
                        setGroupinfo(response.data.data.groupinfo);
                        $("#groupinfoshow").show();

                    });

                }else{
                    layer.msg(response.data.message, {
                        time: 1500,
                        icon: 2,
                        offset: '350px'
                    });
                }
            }).catch(function(error) {
                console.log(error);
            });

        }
    }
};

//定义路由
const routes = [

    {
        path : '/' ,
        component : main ,
        children : [
            //子路由path不需要/
            {path : 'create' , component : create_group_component},
            {path : 'search' , component : search_group_component}
        ]

    }
]

// 创建 router 实例
const routerInstance = new VueRouter({
    routes: routes
});

// 创建 Vue 实例  并注册路由
var chat = new Vue({
    el: '#groupchatvue',
    router : routerInstance
});

//定时提示系统时间
var id =setInterval(function () {
	var min = new Date().getMinutes();
	var sec = new Date().getSeconds();
    if (0==min && 0==sec){   //myDate.getHours();    //获取当前小时数(0-23) 
    	let date = new Date()
    	var df = dateFormat("现在的时间是YYYY年mm月dd日 HH点MM分", date);
    	//提示系统时间，持续10秒
//    	layer.msg(df, {
//            time: 10000,
//            icon: 0,
//            offset: '150px'
//        });
    	sendtoalluser(df);
    }
},1000,id); 

function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}
function sendtoalluser(df){
    var object = new Object();
    object["reciveuserid"] = "sys";
    object["msgtype"] = 0;
    object["sendtext"] = df;
    var jsonData = JSON.stringify(object);
    websocket.send(jsonData);//websocket发送数据
}

//点赞信息同步
function setlive() {
	 $.ajax({
        url: basePath + "/chat/livefriend/"+actuserid,
        data: "",
        contentType: "application/json;charset=UTF-8",
        type: "post",
        success: function (data) {
        },
        error: function (err) {
            console.log("err:", err);
        }
    });
	var message = '小伙子看你骨骼惊奇，给你点赞一个！！';
   var object = new Object();
   object["sendUserId"] = userid;
   object["reciveUserId"] = actuserid;
   object["msgType"] = 0;
   object["sendText"] =message;
   var jsonData = JSON.stringify(object);
   websocket.send(jsonData);//websocket发送数据
   appendmsg("0", actuserid, userid, message);//vue追加聊天数据
   document.getElementById("msg_end").scrollIntoView();
   var span = document.getElementsByName(actuserid)[0];
   var livenum = parseFloat(span.innerText || 0);
   span.innerText=livenum+1;
}

/**
 * 浏览器关闭清理session和redis中的数据
 */
window.addEventListener('beforeunload',function (event) {
    clearSession(event);

},true)

function clearSession(event){
    axios.post('/chat/clearSessionInfo'
    );
}